<div class="container">
  <h1 id="pkg-overview">package context</h1>

  <p><code>import "context"</code>

  </p><p>
Package context defines the Context type, which carries deadlines,
cancelation signals, and other request-scoped values across API boundaries
and between processes.
</p>
<p>
Incoming requests to a server should create a Context, and outgoing
calls to servers should accept a Context. The chain of function
calls between them must propagate the Context, optionally replacing
it with a derived Context created using WithCancel, WithDeadline,
WithTimeout, or WithValue. When a Context is canceled, all
Contexts derived from it are also canceled.
</p>
<p>
The WithCancel, WithDeadline, and WithTimeout functions take a
Context (the parent) and return a derived Context (the child) and a
CancelFunc. Calling the CancelFunc cancels the child and its
children, removes the parent's reference to the child, and stops
any associated timers. Failing to call the CancelFunc leaks the
child and its children until the parent is canceled or the timer
fires. The go vet tool checks that CancelFuncs are used on all
control-flow paths.
</p>
<p>
Programs that use Contexts should follow these rules to keep interfaces
consistent across packages and enable static analysis tools to check context
propagation:
</p>
<p>
Do not store Contexts inside a struct type; instead, pass a Context
explicitly to each function that needs it. The Context should be the first
parameter, typically named ctx:
</p>
<pre>func DoSomething(ctx context.Context, arg Arg) error {
	// ... use ctx ...
}
</pre>
<p>
Do not pass a nil Context, even if a function permits it. Pass context.TODO
if you are unsure about which Context to use.
</p>
<p>
Use context Values only for request-scoped data that transits processes and
APIs, not for passing optional parameters to functions.
</p>
<p>
The same Context may be passed to functions running in different goroutines;
Contexts are safe for simultaneous use by multiple goroutines.
</p>
<p>
See <a href="https://blog.golang.org/context">https://blog.golang.org/context</a> for example code for a server that uses
Contexts.</p>


        
  


        
  
  
        

        

        
        
          
          
        

        
        


<p><a href="https://github.com/golang/go/blob/master/src/context/context.go">context.go</a> </p>

        
        

        
        
          <h2 id="pkg-variables">Variables </h2>
          <p>
Canceled is the error returned by Context.Err when the context is canceled.
</p>
<p>
DeadlineExceeded is the error returned by Context.Err when the context's
deadline passes.
</p>

        
        
          <h2 data-kind="t" id="CancelFunc">type <a href="https://github.com/golang/go/blob/master/src/context/context.go#L221" title="View Source">CancelFunc</a>  </h2>
          <p>
A CancelFunc tells an operation to abandon its work.
A CancelFunc does not wait for the work to stop.
After the first call, subsequent calls to a CancelFunc do nothing.
</p>

          
        
          <h2 data-kind="t" id="Context">type <a href="https://github.com/golang/go/blob/master/src/context/context.go#L62" title="View Source">Context</a>  </h2>
          <p>
A Context carries a deadline, a cancelation signal, and other values across
API boundaries.
</p>
<p>
Context's methods may be called by multiple goroutines simultaneously.
</p>

          
          
          
  


          
            <h3 data-kind="f" id="Background">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L205" title="View Source">Background</a>  </h3>
            <p>
Background returns a non-nil, empty Context. It is never canceled, has no
values, and has no deadline. It is typically used by the main function,
initialization, and tests, and as the top-level Context for incoming
requests.
</p>

            
  

          
            <h3 data-kind="f" id="TODO">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L214" title="View Source">TODO</a>  </h3>
            <p>
TODO returns a non-nil, empty Context. Code should use context.TODO when
it's unclear which Context to use or it is not yet available (because the
surrounding function has not yet been extended to accept a Context
parameter). TODO is recognized by static analysis tools that determine
whether Contexts are propagated correctly in a program.
</p>

            
  

          
            <h3 data-kind="f" id="WithCancel">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L229" title="View Source">WithCancel</a>  </h3>
            <p>
WithCancel returns a copy of parent with a new Done channel. The returned
context's Done channel is closed when the returned cancel function is called
or when the parent context's Done channel is closed, whichever happens first.
</p>
<p>
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete.
</p>

            
  
    <div class="panel-group">
    
      <div class="panel panel-default" id="example-WithCancel">
        <div class="panel-heading"><a class="accordion-toggle" data-toggle="collapse" href="#ex-WithCancel">Example</a></div>
        <div class="panel-collapse collapse" id="ex-WithCancel"><div class="panel-body">
          <p></p><p>
This example demonstrates the use of a cancelable context to prevent a
goroutine leak. By the end of the example function, the goroutine started
by gen will return without leaking.
</p>

          <p>Code:<span class="pull-right"><a href="?play=WithCancel">play</a> </span>
          </p><pre><span class="com">// gen generates integers in a separate goroutine and
// sends them to the returned channel.
// The callers of gen need to cancel the context once
// they are done consuming generated integers not to leak
// the internal goroutine started by gen.</span>
gen := func(ctx context.Context) &lt;-chan int {
    dst := make(chan int)
    n := 1
    go func() {
        for {
            select {
            case &lt;-ctx.Done():
                return <span class="com">// returning not to leak the goroutine</span>
            case dst &lt;- n:
                n++
            }
        }
    }()
    return dst
}

ctx, cancel := context.WithCancel(context.Background())
defer cancel() <span class="com">// cancel when we are finished consuming integers</span>

for n := range gen(ctx) {
    fmt.Println(n)
    if n == 5 {
        break
    }
}</pre>
          <p>Output:</p><pre>1
2
3
4
5
</pre>
        </div></div>
      </div>
    
    </div>
  

          
            <h3 data-kind="f" id="WithDeadline">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L369" title="View Source">WithDeadline</a>  </h3>
            <p>
WithDeadline returns a copy of the parent context with the deadline adjusted
to be no later than d. If the parent's deadline is already earlier than d,
WithDeadline(parent, d) is semantically equivalent to parent. The returned
context's Done channel is closed when the deadline expires, when the returned
cancel function is called, or when the parent context's Done channel is
closed, whichever happens first.
</p>
<p>
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete.
</p>

            
  
    <div class="panel-group">
    
      <div class="panel panel-default" id="example-WithDeadline">
        <div class="panel-heading"><a class="accordion-toggle" data-toggle="collapse" href="#ex-WithDeadline">Example</a></div>
        <div class="panel-collapse collapse" id="ex-WithDeadline"><div class="panel-body">
          <p></p><p>
This example passes a context with a arbitrary deadline to tell a blocking
function that it should abandon its work as soon as it gets to it.
</p>

          <p>Code:<span class="pull-right"><a href="?play=WithDeadline">play</a> </span>
          </p><pre>d := time.Now().Add(50 * time.Millisecond)
ctx, cancel := context.WithDeadline(context.Background(), d)

<span class="com">// Even though ctx will be expired, it is good practice to call its
// cancelation function in any case. Failure to do so may keep the
// context and its parent alive longer than necessary.</span>
defer cancel()

select {
case &lt;-time.After(1 * time.Second):
    fmt.Println("overslept")
case &lt;-ctx.Done():
    fmt.Println(ctx.Err())
}</pre>
          <p>Output:</p><pre>context deadline exceeded
</pre>
        </div></div>
      </div>
    
    </div>
  

          
            <h3 data-kind="f" id="WithTimeout">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L436" title="View Source">WithTimeout</a>  </h3>
            <p>
WithTimeout returns WithDeadline(parent, time.Now().Add(timeout)).
</p>
<p>
Canceling this context releases resources associated with it, so code should
call cancel as soon as the operations running in this Context complete:
</p>
<pre>func slowOperationWithTimeout(ctx context.Context) (Result, error) {
	ctx, cancel := context.WithTimeout(ctx, 100*time.Millisecond)
	defer cancel()  // releases resources if slowOperation completes before timeout elapses
	return slowOperation(ctx)
}
</pre>

            
  
    <div class="panel-group">
    
      <div class="panel panel-default" id="example-WithTimeout">
        <div class="panel-heading"><a class="accordion-toggle" data-toggle="collapse" href="#ex-WithTimeout">Example</a></div>
        <div class="panel-collapse collapse" id="ex-WithTimeout"><div class="panel-body">
          <p></p><p>
This example passes a context with a timeout to tell a blocking function that
it should abandon its work after the timeout elapses.
</p>

          <p>Code:<span class="pull-right"><a href="?play=WithTimeout">play</a> </span>
          </p><pre><span class="com">// Pass a context with a timeout to tell a blocking function that it
// should abandon its work after the timeout elapses.</span>
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()

select {
case &lt;-time.After(1 * time.Second):
    fmt.Println("overslept")
case &lt;-ctx.Done():
    fmt.Println(ctx.Err()) <span class="com">// prints "context deadline exceeded"</span>
}</pre>
          <p>Output:</p><pre>context deadline exceeded
</pre>
        </div></div>
      </div>
    
    </div>
  

          
            <h3 data-kind="f" id="WithValue">func <a href="https://github.com/golang/go/blob/master/src/context/context.go#L453" title="View Source">WithValue</a>  </h3>
            <p>
WithValue returns a copy of parent in which the value associated with key is
val.
</p>
<p>
Use context Values only for request-scoped data that transits processes and
APIs, not for passing optional parameters to functions.
</p>
<p>
The provided key must be comparable and should not be of type
string or any other built-in type to avoid collisions between
packages using context. Users of WithValue should define their own
types for keys. To avoid allocating when assigning to an
interface{}, context keys often have concrete type
struct{}. Alternatively, exported context key variables' static
type should be a pointer or interface.
</p>

            
  
    <div class="panel-group">
    
      <div class="panel panel-default" id="example-WithValue">
        <div class="panel-heading"><a class="accordion-toggle" data-toggle="collapse" href="#ex-WithValue">Example</a></div>
        <div class="panel-collapse collapse" id="ex-WithValue"><div class="panel-body">
          
          <p>Code:
          </p><pre>type favContextKey string

f := func(ctx context.Context, k favContextKey) {
    if v := ctx.Value(k); v != nil {
        fmt.Println("found value:", v)
        return
    }
    fmt.Println("key not found:", k)
}

k := favContextKey("language")
ctx := context.WithValue(context.Background(), k, "Go")

f(ctx, k)
f(ctx, favContextKey("color"))</pre>
          <p>Output:</p><pre>found value: Go
key not found: color
</pre>
        </div></div>
      </div>
    
</div>
<div class="clearfix" id="x-footer">
  <div class="container">
    <a href="http://studygolang.com/" target="_blank">Go语言中文网</a>
    <span class="text-muted">|</span> <a href="http://golang.org/" target="_blank">Go Language</a>
    <span class="pull-right"><a href="#">Back to top</a></span>
  </div>
</div>
<script src="../assets/jquery-2.0.3.min.js" type="text/javascript"></script>
<script src="../assets/bootstrap.min.js" type="text/javascript"></script>
<script src="../assets/site.js" type="text/javascript"></script>


</div>